﻿
using NLog;
using Prism.Commands;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System;
using System.IO;
using System.Linq;
using CCSFeederCameraUI2.Data.Extensions;
using CCSFeederCameraUI2.Data;
using CCSFeederCameraUI2.Data.MClass;
using CCSFeederCameraUI2.Models;
using CCSFeederCameraUI2.Data.ViewModels;

namespace CCSFeederCameraUI2.ViewModels.Dialogs
{
    public class PartNumDialogViewModel : DialogViewModel
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        #endregion
        #region 属性绑定
        private string currentPartNum;
        public string CurrentPartNum
        {
            get { return currentPartNum; }
            set { SetProperty(ref currentPartNum, value); }
        }
        private ObservableCollection<MyPartNum> partNumbList;
        public ObservableCollection<MyPartNum> PartNumbList
        {
            get { return partNumbList; }
            set { SetProperty(ref partNumbList, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand addCommand;
        public DelegateCommand AddCommand =>
            addCommand ?? (addCommand = new DelegateCommand(ExecuteAddCommand));
        private DelegateCommand<MyPartNum> deleteCommand;
        public DelegateCommand<MyPartNum> DeleteCommand =>
            deleteCommand ?? (deleteCommand = new DelegateCommand<MyPartNum>(ExecuteDeleteCommand));
        private DelegateCommand<MyPartNum> selectCommand;
        public DelegateCommand<MyPartNum> SelectCommand =>
            selectCommand ?? (selectCommand = new DelegateCommand<MyPartNum>(ExecuteSelectCommand));

        void ExecuteSelectCommand(MyPartNum partNum)
        {
            if (partNum != null)
            {
                if (partNum.Name != CurrentPartNum)
                {

                    if (MessageBox.Show($"确认切换为\"{partNum.Name}\"料号吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                    {
                        using var mdb = new MDbContext();
                        var param = mdb.MParams.FirstOrDefault(p => p.Name == "PartNum");
                        if (param != null)
                        {
                            CurrentPartNum = param.Value = partNum.Name;
                            mdb.SaveChanges();
                        }
                        aggregator.SendMessage($"PartNumChanged;{partNum.Name}", "Run");
                        aggregator.SendMessage("ReloadParam", "Run");
                        aggregator.SendMessage($"PartNum;{partNum.Name}", "MES");
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDeleteCommand(MyPartNum partNum)
        {
            if (partNum != null)
            {
                if (partNum.Name != CurrentPartNum)
                {
                    if (MessageBox.Show($"确定删除料号\"{partNum.Name}\"吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                    {
                        try
                        {
                            //删除文件夹
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partNum.Name));
                            di.Delete(true);
                            using var mdb = new MDbContext();
                            var _partnum = mdb.PartNums.FirstOrDefault(p => p.Name == partNum.Name);
                            if (_partnum != null)
                            {
                                mdb.PartNums.Remove(_partnum);
                                mdb.SaveChanges();
                                PartNumbList.Clear();
                                var _partnums = mdb.PartNums.Where(p => p.Name != string.Empty);
                                if (_partnums.Any())
                                {
                                    var _list = _partnums.ToList();
                                    for (int i = 0; i < _list.Count; i++)
                                    {
                                        PartNumbList.Add(new MyPartNum
                                        {
                                            Id = i + 1,
                                            Name = _list[i].Name
                                        });
                                    }
                                }
                            }
                           
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("不能删除当前料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteAddCommand()
        {
            dialogService.ShowDialog("AddNewPartNumDialog", arg =>
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    var newpartName = arg.Parameters.GetValue<string>("NewPartNumName");
                    if (newpartName != string.Empty)
                    {
                        using var mdb = new MDbContext();
                        var _partnum = mdb.PartNums.FirstOrDefault(p => p.Name == newpartName);
                        if (_partnum == null)
                        {
                            try
                            {
                                //创建新文件夹
                                Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, newpartName));

                                //复制数据                                        
                                FileHelper.DirectoryCopy(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, CurrentPartNum), System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, newpartName), true);
                                mdb.PartNums.Add(new Data.MClass.PartNum { 
                                    Name = newpartName
                                });
                                mdb.SaveChanges();
                                PartNumbList.Clear();
                                var _partnums = mdb.PartNums.Where(p => p.Name != string.Empty);
                                if (_partnums.Any())
                                {
                                    var _list = _partnums.ToList();
                                    for (int i = 0; i < _list.Count; i++)
                                    {
                                        PartNumbList.Add(new MyPartNum
                                        {
                                            Id = i + 1,
                                            Name = _list[i].Name
                                        });
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"料号\"{newpartName}\"已存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("料号名不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
     
            try
            {
                using var mdb = new MDbContext();
                var param = mdb.MParams.FirstOrDefault(p => p.Name == "PartNum");
                if (param != null)
                {
                    CurrentPartNum = param.Value;
                }
                else
                {
                    CurrentPartNum = "Test";
                    mdb.MParams.Add(new MParam
                    {
                        Name = "CurrentPartNum",
                        Value = CurrentPartNum.ToString()
                    });
                    mdb.SaveChanges();
                }
                var _partnums = mdb.PartNums.Where(p => p.Name != string.Empty);
                if (_partnums.Any())
                {
                    var _list = _partnums.ToList();
                    for (int i = 0; i < _list.Count; i++)
                    {
                        PartNumbList.Add(new MyPartNum
                        {
                            Id = i + 1,
                            Name = _list[i].Name
                        });
                    }
                }
                else
                {
                    mdb.PartNums.Add(new  Data.MClass.PartNum {
                        Name = "Test"
                    });
                    mdb.SaveChanges();
                    PartNumbList.Add(new MyPartNum
                    {
                        Id = 1,
                        Name = "Test"
                    });
                }
                Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, CurrentPartNum));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        #endregion
        public PartNumDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            PartNumbList = new ObservableCollection<MyPartNum>();
        }
        #region 功能函数

        #endregion
    }
    public class MyPartNum
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
